import { BASEURL, TOKEN } from '@/assets/js/config.js'
import { storage, loginOutQ } from './utils'
import { useStore } from '@/store'
const store = useStore()
// 请求错误提示
// eslint-disable-next-line node/handle-callback-err
const showError = (error, message, successCallback) => {
  uni.showToast({
    title: message,
    duration: 2000,
    icon: 'none',
    mask: true,
    success: res => {
      successCallback && typeof successCallback === 'function' && successCallback()
    }
  })
}
// 500错误提示
const globalError = (response) => {
  uni.showModal({
    title: String(response.code),
    content: response.msg,
    confirmText: '确定',
    showCancel: false
  })
}
const interceptorsRequest = (method, url, data, type, header = {}) => {
  return {
    method,
    url,
    data,
    type,
    header
  }
}
const request = ({
  method = 'get',
  url,
  data,
  type,
  header = {}
}) => {
  const params = interceptorsRequest(method, url, data, type, header)
  params.header['Content-Type'] = 'application/json; charset=utf-8'
  const TokenStore = storage.get(TOKEN) || store.state.token
  if (TokenStore) {
    params.header.Authorization = TokenStore
  }
  params.header.endpoint = 'PICO'
  // #ifdef H5
  params.header.platform = 'H5'
  // #endif
  // #ifdef MP-WEIXIN
  params.header.platform = 'MP'
  // #endif
  return new Promise((resolve, reject) => {
    let url = ''
    params.type = 'public'
    url = BASEURL + '/' + params.type + '/v1' + params.url
    const map = /^\/map/
    if (map.test(params.url)) {
      url = params.url.replace(map, 'https://apis.map.qq.com')
    }
    console.log(url)
    uni.request({
      method,
      url,
      header: params.header,
      data: params.data,
      withCredentials: true,
      success: (res) => {
        const resData = res.data
        if (res.statusCode === 200) {
          if (resData.code === 600603 || resData.code === 600401 || resData.code === 600403 || resData.code === 600402) {
            // 登录过期过期逻辑，在全局的profile请求不需要登录
            // const _method = method.toLocaleLowerCase()
            const _Arr = [
              '/center/message/num',
              '/profile',
              '/app/geo',
              '/app/eventsInfo/enroll/latest'
            ]
            if (_Arr.indexOf(params.url) !== -1 && params.data) {
              loginOutQ(store, storage)
            } else {
              storage.remove(TOKEN)
              // eslint-disable-next-line no-undef
              const len = getCurrentPages().length
              uni.redirectTo({
                // eslint-disable-next-line no-undef
                url: `/pages/login?redirect=${encodeURIComponent(getCurrentPages()[len - 1].$page.fullPath)}`
              })
            }
            // reject(resData)
          } else if (resData.code === 0) {
            resolve(resData)
          } else {
            // 暂时注释
            showError('糟糕！出错了', resData.msg || '请联系客服')
            // showError('糟糕！出错了', resData.msg)
            resolve(resData)
          }
        } else {
          reject(resData.msg)
          globalError({
            code: 500,
            msg: '500'
          })
        }
      },
      fail: err => {
        const MODE = import.meta.env.MODE // 当前的环境，dev才会弹出网络框
        if (MODE === 'development') {
          uni.showModal({
            title: '网络',
            content: '网络出现问题，请检查网络是否连接畅通！',
            confirmText: '确定',
            showCancel: false
          })
        }
        reject(err)
      }
    })
  })
}

export default request
